/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2022-05-17     fanlulin       the first version
 */


#include "cloud.h"

/* 指向信号量的指针
 * 在wifi连接成功后再启动zzy线程，来连接中智云平台，进行数据传输。
 *  */

//static rt_sem_t net = RT_NULL;



//连接zzy的线程
static rt_thread_t zzy = RT_NULL;




//连接zzy的入口函数
void zzy_entry(void *parameter)
{
    //rt_sem_take(net, 0);
    rt_kprintf("zzy entry\r\n");
    int ret;
    char *recv_data;
    struct hostent *host;
    int sock, bytes_received;
    struct sockaddr_in server_addr;
    const char *url;
    int port;

    url = "api.zhiyun360.com";
    port = 28082;

    /* 通过函数入口参数url获得host地址（如果是域名，会做域名解析） */
    host = gethostbyname(url);

    /* 分配用于存放接收数据的缓冲 */
    recv_data = rt_malloc(BUFSZ);
    if (recv_data == RT_NULL)
    {
        rt_kprintf("No memory\n");
        return;
    }

    /* 创建一个socket，类型是SOCKET_STREAM，TCP类型 */
    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1)
    {
        /* 创建socket失败 */
        rt_kprintf("Socket error\n");

        /* 释放接收缓冲 */
        rt_free(recv_data);
        return;
    }

    /* 初始化预连接的服务端地址 */
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(port);
    server_addr.sin_addr = *((struct in_addr *)host->h_addr);
    rt_memset(&(server_addr.sin_zero), 0, sizeof(server_addr.sin_zero));

    /* 连接到服务端 */
    if (connect(sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1)
    {
        /* 连接失败 */
        rt_kprintf("zzy Connect fail!\n");
        closesocket(sock);

        /*释放接收缓冲 */
        rt_free(recv_data);
        return;
    }
    else
    {
        /* 连接成功 */
        rt_kprintf("zzy Connect successful\n");
    }


    return;
}




//连接中智云的线程
int zzy_thread(void){
    zzy = rt_thread_create("zzy",
                            zzy_entry, RT_NULL,
                            THREAD_STACK_SIZE,
                            THREAD_PRIORITY, THREAD_TIMESLICE);
    if (zzy != RT_NULL){
        rt_thread_startup(zzy);
        rt_kprintf("zzy thread start successfully\r\n");
    }

    else{
        rt_kprintf("zzy thread start failed\r\n");
    }
    return 0;
}

//MSH_CMD_EXPORT(zzy_thread, a tcp client sample);
